package net.liteheaven.xblib.common.io.reborn;

import android.content.Context;
import android.text.TextUtils;

import com.google.gson.Gson;

import java.util.Map;

/**
 * 安卓重生动作管理类
 * Created by liangy on 2017/1/20.
 */
public class RebornManager {

    private static RebornManager sInstance;

    public static RebornManager getInstance(){
        if (sInstance == null){
            sInstance = new RebornManager();
        }
        return sInstance;
    }

    private RebornManager(){

    }

    public void bury(Context context, String type, RebornAction action){
        String str = encode(action);
        RebornSpHelper.push(context, type, str);
    }

    public void reborn(Context context, String type){
        Map<String, ?> valueMap = RebornSpHelper.popAll(context, type);
        for (Map.Entry<String, ?> entry : valueMap.entrySet()){
            String value = (String)entry.getValue();
            RebornAction action = decode(value);
            if (action != null){
                action.onExecute(context);
            }
        }
    }

    private String encode(RebornAction action){
        String content;
        try{
            content = new Gson().toJson(action);
        }catch (Exception e){
            e.printStackTrace();
            return "";
        }

        RebornBean bean = new RebornBean();
        bean.className = action.getClass().getName();
        bean.content = content;

        String str = "";
        try{

            str = new Gson().toJson(bean);
        }catch (Exception e){
            e.printStackTrace();
        }

        if (str == null){
            str = "";
        }
        return str;
    }

    private RebornAction decode(String str){
        RebornAction action = null;
        if (!TextUtils.isEmpty(str)){
            try{
                RebornBean bean = new Gson().fromJson(str, RebornBean.class);
                if (bean != null){
                    Class<?> clazz = Class.forName(bean.className);
                    action = (RebornAction) new Gson().fromJson(bean.content, clazz);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return action;
    }

    private static class RebornBean{
        public String className;
        public String content;
    }
}
